package com.etheart.usersphere.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.etheart.framework.core.dao.CrudService;
import com.etheart.framework.core.dao.QueryService;
import com.etheart.framework.core.util.MD5;
import com.etheart.model.entity.User;
import com.etheart.model.enums.EnableState;

@Service("usersphere_UserService")
public class UserServiceImp implements UserService {
	@Autowired
	private QueryService queryService;
	@Autowired
	private CrudService crudService;

	public User getLogin(String username,String password){
		User user = getUserByUsername(username);
		if (user==null) {
			return null;
		}
		if (matchingPassword(user, password)) {
			return user;
		} 
		return null;
	}

	public User getUserByUsername(String username) {
		User user = new User();
		user.setUsername(username);
		List<User> users = queryService.findByExample(user);
		if (users.size()>0) {
			return users.get(0);
		}
		return null;
	}

	public User getUserById(Long userid) {
		return queryService.findById(User.class, userid);
	}

	public void updateUser(User u) {
		crudService.update(u);
	}

	public boolean matchingPassword(User u, String password) {
		if (StringUtils.equals(MD5.md5(password+u.getSalt()), u.getPassword())) {
			return true;
		}
		return false;
	}

	public void modifyPassword(User u, String newPass) {
		u.setPassword(MD5.md5(newPass+u.getSalt()));
		updateUser(u);
	}

	public void registerUser(User user) {
		user.setRegisterTime(new Date());
		user.setSalt(String.valueOf(RandomUtils.nextLong()));
		user.setDisabled(EnableState.ENABLED);
		crudService.create(user);
	}
}
